package zheezes.protocol.impl.gd.converter;

import java.math.BigDecimal;
import java.util.Arrays;

import zheezes.util.ArrayUtil;
import zheezes.util.ByteUtil;


public class MeterValueConverter {
	public static final BigDecimal btov(byte[] buf) {
		return btov(buf, 0);
	}

	public static final BigDecimal btov(byte[] buf, int offset) {
		try {
			return new BigDecimal(ArrayUtil.sprintf(buf, offset, 4, "%02X")).movePointLeft(2);
		} catch (NumberFormatException e) { // avoid [FF]
		}
		return null;
	}

	public static final byte[] vtob(BigDecimal value) {
		byte[] buf = new byte[4];
		vtob(buf, 0, value);
		return buf;
	}

	public static final int vtob(byte[] buf, int offset, BigDecimal value) {
		if(value != null) {
			Arrays.fill(buf, offset, offset + 4, (byte) 0);
			byte[] arr = ByteUtil.longToBcd(value.movePointRight(2).longValue());
			System.arraycopy(arr, 0, buf, offset + (4 - arr.length), arr.length);
		} else {
			Arrays.fill(buf, offset, offset + 4, (byte) 0xFF);
		}

		return 4;
	}
}
